package com.photography.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.common.JwtTokenUtils;
import com.photography.common.Result;
import com.photography.entity.ShippingAddress;
import com.photography.exception.ErrorCode;
import com.photography.mapper.ShippingAddressMapper;
import com.photography.service.ShippingAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Objects;


@Service
public class ShippingAddressServiceImpl extends ServiceImpl<ShippingAddressMapper, ShippingAddress> implements ShippingAddressService {

    private Integer getLoginUserId() {
        return Objects.requireNonNull(JwtTokenUtils.getCurrentUser()).getUserId();
    }

    private void setAddressNonDefault(Integer userId) {
        ShippingAddress shippingAddress = new ShippingAddress();
        shippingAddress.setIsDefault(false);
        LambdaQueryWrapper<ShippingAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShippingAddress::getUserId, userId);
        this.update(shippingAddress, queryWrapper);
    }

    /**
     * 新增收货地址
     *
     * @param address 地址信息
     * @return 结果
     */
    @Override
    public Result addAddress(ShippingAddress address) {
        // 参数校验
        if (address.getUserId() == null) {
            return Result.error("用户ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!address.getUserId().equals(getLoginUserId())) {
            return Result.error("不能使用他人id");
        }
        if (!StringUtils.hasText(address.getRecipientName())) {
            return Result.error("收货人姓名不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(address.getPhoneNumber())) {
            return Result.error("手机号码不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(address.getProvince())) {
            return Result.error("省份不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(address.getCity())) {
            return Result.error("城市不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(address.getDistrict())) {
            return Result.error("区县不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (!StringUtils.hasText(address.getStreetAddress())) {
            return Result.error("详细地址不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        // 设置默认值
        if (address.getIsDefault() == null) {
            address.setIsDefault(false);
        }
        Date now = new Date();
        address.setCreateTime(now);
        address.setUpdateTime(now);
        // 如果设置为默认地址，则取消其他默认地址
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            setAddressNonDefault(address.getUserId());
        }
        boolean result = this.save(address);
        if (result) {
            return Result.success(address, "添加收货地址成功");
        } else {
            return Result.error("添加收货地址失败");
        }
    }

    /**
     * 删除收货地址
     *
     * @param id 地址id
     * @return 结果
     */
    @Override
    public Result deleteAddress(Integer id) {
        if (id == null) {
            return Result.error("地址id不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        ShippingAddress haveShipping = this.getById(id);
        if (haveShipping == null) {
            return Result.error("此收货地址不存在", ErrorCode.DATA_NOT_EXIST.getCode());
        }
        if (!this.getById(id).getUserId().equals(getLoginUserId())) {
            return Result.error("只能删除自己的收货地址");
        }
        boolean result = this.removeById(id);
        if (result) {
            return Result.success(null, "删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 修改收货地址
     *
     * @param address 修改地址信息
     * @return 结果
     */
    @Override
    public Result updateAddress(ShippingAddress address) {
        if (address.getId() == null) {
            return Result.error("地址id不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        ShippingAddress shippingAddress = this.getById(address.getId());
        if (shippingAddress == null) {
            return Result.error("无此地址信息", ErrorCode.DATA_NOT_EXIST.getCode());
        }
        if (!this.getById(address.getId()).getUserId().equals(getLoginUserId())) {
            return Result.error("只能修改自己的收货地址");
        }
        if(address.getIsDefault()){
            setAddressNonDefault(getLoginUserId());
            LambdaQueryWrapper<ShippingAddress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShippingAddress::getId, address.getId());
            address.setIsDefault(true);
           this.update(address, queryWrapper);
        }
        boolean result = this.updateById(address);
        if (result) {
            return Result.success(address, "修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 设置默认收货地址
     *
     * @param id 地址id
     * @return 结果
     */
    @Override
    public Result setDefaultAddress(Integer id) {
        if (id == null) {
            return Result.error("地址id不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        ShippingAddress address = getById(id);
        if (address == null) {
            return Result.error("无此地址");
        }
        if (!this.getById(id).getUserId().equals(getLoginUserId())) {
            return Result.error("只能设置自己的收货地址");
        }
        setAddressNonDefault(getLoginUserId());

        LambdaQueryWrapper<ShippingAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShippingAddress::getId, id);
        address.setIsDefault(true);
        boolean result = this.update(address, queryWrapper);
        if (result) {
            return Result.success(null, "设置成功");
        }
        return Result.error("设置失败");
    }


    /**
     * 根据用户ID分页查询收货地址
     *
     * @param page 分页信息
     * @return 结果
     */
    @Override
    public Page<ShippingAddress> getAddressPage(Page<ShippingAddress> page) {
        LambdaQueryWrapper<ShippingAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShippingAddress::getUserId, getLoginUserId()).orderByDesc(ShippingAddress::getIsDefault);
        return page(page, queryWrapper);
    }
}
